import {login, getInfo, logout, register, getUserInfoByToken, resetPassword} from '@/api/login'

const tokenKey = 'Authorization'
const refreshTokenKey = 'refresh_Authorization'
const accessTokenExpireDateKey = 'accessTokenExpireDate'
const usernameKey = 'usernameKey'
const userIdKey = 'userIdKey'

function resetState (commit) {
  commit('SET_TOKEN', '')
  commit('SET_REFRESH_TOKEN', '')
  commit('SET_USERNAME', '')
  commit('SET_ROLES', [])
  commit('SET_PERMISSIONS', [])
  commit('SET_CURRENT_PROJECT', undefined)
  commit('SET_CURRENT_TODO', undefined)
  commit('SET_CURRENT_MENU', undefined)
  commit('SET_USERID', undefined)
}

const user = {
  state: {
    token: localStorage.getItem(tokenKey) ? localStorage.getItem(tokenKey) : '',
    refreshToken: localStorage.getItem(refreshTokenKey) ? localStorage.getItem(refreshTokenKey) : '',
    accessTokenExpireDate: localStorage.getItem(accessTokenExpireDateKey) ? localStorage.getItem(accessTokenExpireDateKey) : '',
    username: localStorage.getItem(usernameKey) ? localStorage.getItem(usernameKey) : 'user',
    roles: [],
    permissions: [],
    userId: localStorage.getItem(userIdKey) ? parseInt(localStorage.getItem(userIdKey)) : undefined
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      localStorage.setItem(tokenKey, token)
    },
    SET_TOKEN_EXPIRED: (state, expireDate) => {
      state.accessTokenExpireDate = expireDate
      localStorage.setItem(accessTokenExpireDateKey, expireDate)
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      state.refreshToken = refreshToken
      localStorage.setItem(refreshTokenKey, refreshToken)
    },
    SET_USERNAME: (state, username) => {
      state.username = username
      localStorage.setItem(usernameKey, username)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
      localStorage.setItem(userIdKey, userId)
    }
  },
  actions: {
    // 登录
    Login ({ commit }, formData) {
      const username = formData.username.trim()
      const password = formData.password
      const inputCode = formData.inputCode
      const uuid = formData.uuid
      return new Promise((resolve, reject) => {
        login(username, password, inputCode, uuid).then(res => {
          commit('SET_TOKEN', res.data['access_token'])
          commit('SET_REFRESH_TOKEN', res.data['refresh_token'])
          commit('SET_TOKEN_EXPIRED', res.data['expireMills'])
          commit('SET_IS_LOGGED', true)
          getUserInfoByToken().then(res => {
            commit('SET_USERNAME', res.data.userName)
            commit('SET_USERID', parseInt(res.data.userId))
          })
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    Register ({ commit }, formData) {
      const email = formData.email
      const password = formData.pwd
      const rePassword = formData.repwd
      const inputCode = formData.inputCode
      const uuid = formData.uuid
      return new Promise((resolve, reject) => {
        register(email, password, rePassword, inputCode, uuid).then(res => {
          console.log('注册数据：')
          console.log(res)
          commit('SET_TOKEN', res.data.token)
          getUserInfoByToken().then(res => {
            commit('SET_USERNAME', res.data.userName)
            commit('SET_USERID', res.data.userId)
          })
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo ({ commit, state }, userId) {
      return new Promise((resolve, reject) => {
        getInfo(userId).then(res => {
          const user = res
          // TODO: 对接后端接口完成权限拉取
          commit('SET_USERNAME', user.username)
          commit('SET_ROLES', user.roles)
          commit('SET_PERMISSIONS', user.permissions)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token, state.refreshToken).then(() => {
          resetState(commit)
          commit('SET_IS_LOGGED', false)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        resolve()
      })
    },
    ResetPassword ({ commit }, formData) {
      return new Promise((resolve, reject) => {
        resetPassword(formData.password, formData.rePassword).then(res => {
          commit('SET_IS_LOGGED', false)
          resetState(commit)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
export default user
